<template>
  <el-container class="custom-container-style">
    <div class="custom-adhibition-header">
      <div class="adhibition-header-l"></div>
      <div class="adhibition-header-m">
         <h1>网格化综合应用平台</h1>
         <div class="custom-adhibition-menu-style">
          <ul>
            <li v-for="(item, index) in menus" :key="index" @click="getItem(item, index)">{{item.name}}</li>
            <span class="nav_active" :style="{left:activePos}"></span>
          </ul>
        </div>
        <a class="backHome" title="返回首页" @click="handleClickBack" href="javascript:;"><em class="iconfont el-icon-extend-shouye" style="font-size: 32px;color: #1ab2ca"></em></a>
      </div>
      <div class="adhibition-header-r"></div>
    </div>
    <div id="shizhanContainer"></div>
    <div id="panel" class="scrollbar1" v-if="panelShow">
      <el-collapse v-model="activeName" accordion id="myList">
        <el-collapse-item v-for='(item, index) in dom' :title="item.name" :name="index" :key="index" >
          <div :id="'myListItem'+ index"></div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <el-dialog :visible.sync="dialogAppFormVisible" :title="dialogAppFormTitle" :before-close="cancel" :close-on-click-modal="false">
      <app-form :formInfo="formInfo"></app-form>
    </el-dialog>
    <div class="custom-mapInfo-style">
      <router-view v-on:transmit="setData"/>
    </div>
  </el-container>
</template>

<script>
import AppForm from '@/components/AppForm'
import {getFormInfo} from '@/utils/setFormInfo'
import {getMapLocationDown} from '@/http/AppApi'
import {getDetailHouseholdPopulation} from '@/http/PopulationApi'
import {getUserPermissionTree, getActiveModuleId, getUserGridTree} from '@/utils/SessionDataUtil'
export default {
  data () {
    return {
      renderData: null,
      formInfo: null,
      AMapUI: null,
      AMap: null,
      map: null,
      menus: [],
      mapInfo: [],
      menuList: [],
      markerList: [],
      currentGridIds: [],
      dom: [],
      panelShow: false,
      isClearMap: false,
      dialogAppFormTitle: '',
      dialogAppFormVisible: false,
      activeName: 0,
      gridZoom: {
        '06': 14.1, '05': 12.13, '04': 10.6, '03': 9.5
      },
      activePos: 0
    }
  },
  components: {
    AppForm
  },
  mounted () {
    this.init()
    this.getMenus()
    this.setMenuActive()
  },
  methods: {
    init () {
      this.AMapUI = window.AMapUI
      this.AMap = window.AMap
      let mapConfig = {
        resizeEnable: true,
        zoom: 10.8,
        viewMode: '3D',
        pitch: 40,
        cityName: '信阳市',
        center: [114.091104, 32.148489]
      }
      this.$nextTick(() => {
        this.map = new AMap.Map('shizhanContainer', mapConfig)
        this.map.setMapStyle('amap://styles/blue')
        this.map.on('complete', this.loadAreaPolygon)
      })
    },
    setData (data) {
      this.AMapUI = window.AMapUI
      this.mapInfo = data
      this.dom = data
      this.panelShow = this.mapInfo && this.mapInfo.length > 0
      this.renderData = []
      if (this.markerList.length > 0) {
        for (const key in this.markerList) {
          if (this.markerList.hasOwnProperty(key)) {
            this.markerList[key].clearData()
            this.markerList = []
          }
        }
      }
      for (let i = 0; i < data.length; i++) {
        const element = data[i]
        const id = 'myListItem' + i
        if (i === 0) {
          this.isClearMap = true
          this.loadMarkerList(id, element.items)
        } else {
          this.isClearMap = false
          this.loadMarkerList(id, element.items)
        }
      }
    },
    loadMarkerList (id, element) {
      let m = this
      this.AMapUI.loadUI(['misc/MarkerList', 'overlay/SimpleMarker', 'overlay/SimpleInfoWindow'], function (MarkerList, SimpleMarker, SimpleInfoWindow) {
        let defaultIconStyle = 'red'
        let hoverIconStyle = 'green'
        let selectedIconStyle = 'purple'
        let markerList = new MarkerList({
          map: m.map,
          listContainer: id,
          getPosition: function (item) {
            if (item.longitude && item.latitude) {
              return [item.longitude, item.latitude]
            } else {
              return [0, 0]
            }
          },
          getDataId: function (item, index) {
            return item.id
          },
          getInfoWindow: (data, context, recycledInfoWindow) => {
            if (recycledInfoWindow) {
              recycledInfoWindow.setInfoTitle(data.name)
              recycledInfoWindow.setInfoBody(data.community + '<br/>' + data.building)
              return recycledInfoWindow
            }
            return new SimpleInfoWindow({
              infoTitle: data.name,
              infoBody: data.community + '<br/>' + data.building,
              offset: new AMap.Pixel(0, -37)
            })
          },
          // 构造marker用的options对象, content和title支持模板，也可以是函数，返回marker实例，或者返回options对象
          getMarker: function (data, context, recycledMarker) {
            var label = String.fromCharCode('A'.charCodeAt(0) + context.index)

            if (recycledMarker) {
              recycledMarker.setIconLabel(label)
              return
            }
            return new SimpleMarker({
              containerClassNames: 'my-marker',
              iconStyle: defaultIconStyle,
              iconLabel: label
            })
          },
          getListElement: (data, context, recycledListElement) => {
            var label = context.index + 1
            // 使用模板创建
            var innerHTML = MarkerList.utils.template('<div class="poi-info-left">' +
              '    <h3 class="poi-title">' +
              '        <%- label %>. <%- data.name %>' +
              '    </h3>' +
              '    <div class="poi-info">' +
              '        <span class="poi-community">' +
              '            <%- data.community %>' +
              '        </span>' +
              '        <p class="poi-addr">' +
              '            <%- data.building %>' +
              '        </p>' +
              '        <p class="poi-addr"><%- data.household %></p>' +
              '    </div>' +
              '</div>' +
              '<div class="clear"></div>', {
              data: data,
              label: label
            })
            if (recycledListElement) {
              recycledListElement.innerHTML = innerHTML
              return recycledListElement
            }
            return '<div class="poibox">' +
              innerHTML +
              '</div>'
          },
          // 列表节点上监听的事件
          listElementEvents: ['click', 'mouseenter', 'mouseleave'],
          // marker上监听的事件
          markerEvents: ['click', 'mouseover', 'mouseout'],
          makeSelectedEvents: false,
          selectedClassNames: 'selected',
          autoSetFitView: false
        })
        m.markerList.push(markerList)
        window.markerList = markerList
        markerList.on('markerClick', function (event, info) {
          m.detailForm = info.data
          m.showInfoFn(info)
          // m.$refs.childComponent.dialogShow()
        })
        markerList.on('selectedChanged', function (event, info) {
          if (info.selectAgain) return ''
          if (info.selected) {
            if (info.selected.marker) {
              // 更新为选中样式
              info.selected.marker.setIconStyle(selectedIconStyle)
            }
            // 选中并非由列表节点上的事件触发，将关联的列表节点移动到视野内
            if (info.selected.listElement) {
              // 设置选中list、样式
              info.selected.listElement.style.backgroundColor = '#ccc'
              let parent = info.selected.listElement.offsetParent.childNodes[0]
              if (parent && parent.childNodes) {
                for (const key in parent.childNodes) {
                  if (parent.childNodes.hasOwnProperty(key) && parent.childNodes[key] !== info.selected.listElement) {
                    parent.childNodes[key].style.backgroundColor = 'unset'
                  }
                }
              }
            }
          }
          if (info.unSelected && info.unSelected.marker) {
            // 更新为默认样式
            info.unSelected.marker.setIconStyle(defaultIconStyle)
          }
        })
        // markerList.on('listElementClick', function (event, record) {
        //   let allMarker = markerList.getAllMarkers()
        //   for (let i = 0; i < allMarker.length; i++) {
        //     const element = allMarker[i]
        //     if (element) {
        //       element.setIconStyle(defaultIconStyle)
        // markerList.on('selectedChanged', function (event, info) {
        //   console.log(info)
        //   if (info.selectAgain) return ''
        //   if (info.selected) {
        //     if (info.selected.marker) {
        //       // 更新为选中样式
        //       info.selected.marker.setIconStyle(selectedIconStyle)
        //     }
        //     // 选中并非由列表节点上的事件触发，将关联的列表节点移动到视野内
        //     if (info.selected.listElement) {
        //       // 设置选中list、样式
        //       info.selected.listElement.style.backgroundColor = '#ccc'
        //       let parent = info.selected.listElement.offsetParent.childNodes[0]
        //       if (parent && parent.childNodes) {
        //         for (const key in parent.childNodes) {
        //           if (parent.childNodes.hasOwnProperty(key) && parent.childNodes[key] !== info.selected.listElement) {
        //             parent.childNodes[key].style.backgroundColor = 'unset'
        //           }
        //         }
        //       }
        //     }
        //   }
        //   if (info.unSelected && info.unSelected.marker) {
        //     // 更新为默认样式
        //     info.unSelected.marker.setIconStyle(defaultIconStyle)
        //   }
        // })
        markerList.on('listElementClick', function (event, record) {
          let allMarker = markerList.getAllMarkers()
          for (let i = 0; i < allMarker.length; i++) {
            const element = allMarker[i]
            if (element) {
              element.setIconStyle(defaultIconStyle)
            }
          }
          // console.log(markerList)
          if (record && record.marker) {
            // console.log(record.marker)
            if (record.position.lng === 0 && record.position.lat === 0) {
              m.detailForm = record.data
              m.$refs.childComponent.dialogShow()
            } else {
              let position = new AMap.LngLat(record.position.lng, record.position.lat)
              m.map.setCenter(position)
              record.marker.setIconStyle(selectedIconStyle)
              record.marker.setTop(true)
            }
          } else {
            m.$message({
              type: 'info',
              message: '没有经纬度数据'
            })
          }
          record.listElement.classList.add('selected')
          let parent = record.listElement.parentNode
          if (parent && parent.childNodes) {
            for (const key in parent.childNodes) {
              if (parent.childNodes.hasOwnProperty(key) && parent.childNodes[key] !== record.listElement) {
                parent.childNodes[key].classList.remove('selected')
              }
            }
          }
        })
        markerList.on('listElementMouseenter markerMouseover', function (event, record) {
          if (record && record.marker) {
            // this.openInfoWindowOnRecord(record)
            // 非选中的id
            if (!this.isSelectedDataId(record.id)) {
              // 设置为hover样式
              record.marker.setIconStyle(hoverIconStyle)
              // this.closeInfoWindow();
            }
          }
        })
        markerList.on('listElementMouseleave markerMouseout', function (event, record) {
          if (record && record.marker) {
            if (!this.isSelectedDataId(record.id)) {
              // 恢复默认样式
              record.marker.setIconStyle(defaultIconStyle)
            }
          }
        })
        let newData = []
        if (m.renderData) {
          for (const i in m.renderData) {
            if (m.renderData.hasOwnProperty(i)) {
              newData.push(m.renderData[i])
            }
          }
        }
        for (const k in element) {
          if (element.hasOwnProperty(k)) {
            newData.push(element[k])
          }
        }
        console.log(newData)
        markerList.render(newData)
      })
    },
    showInfoFn (info) {
      let data = info.data
      let label = data.formName
      this.dialogAppFormTitle = data.name
      let m = this
      const request = {
        '户籍人口': () => {
          getDetailHouseholdPopulation(data.id).then(resp => {
            if (resp.code && resp.code === '200') {
              m.dialogAppFormVisible = true
              m.formInfo = getFormInfo(resp.data, '户籍人口')
            }
          })
        }
      }
      request[label]()
    },
    setMenuActive () {
      let index = sessionStorage.getItem('currentApplicationKey')
      if (index) {
        this.activePos = index * 246 + 'px'
      } else {
        this.activePos = 0
      }
    },
    loadAreaPolygon () {
      let tree = getUserGridTree()
      this.currentGridIds = []
      let m = this
      if (tree && tree instanceof Array) {
        m.treeData = tree
        if (tree.length > 0) {
          for (const key in tree) {
            if (tree.hasOwnProperty(key)) {
              let level = tree[key].levelCode
              m.map.setZoom(m.gridZoom[level])
              m.currentGridIds.push(tree[key].id)
              m.loadMapFun(tree[key].id)
            }
          }
        }
      }
    },
    loadMapFun (id) {
      let m = this
      this.loadGridMap(id).then(function (data) {
        for (const j in data) {
          if (data.hasOwnProperty(j)) {
            m.createPolygon(data[j])
          }
        }
        m.map.panBy(0, -34)
      }).catch(function (reason, data) {
      })
    },
    loadGridMap (id) {
      var promise = new Promise(function (resolve, reject) {
        getMapLocationDown(id).then(resp => {
          if (resp.code && resp.code === '200') {
            resolve(resp.data)
          } else {
            reject(resp.message)
          }
        })
      })
      return promise
    },
    createPolygon (p) {
      if (p) {
        if (this.currentGridIds.indexOf(p.targetId) > -1) {
          this.map.setCenter([p.longitude, p.latitude])
          return ''
        }
        let poly = {}
        if (p.mapColor) {
          poly.fillColor = p.mapColor
          poly.strokeColor = p.mapColor
          poly.fillOpacity = 0.3
          // poly.strokeOpacity = 0
        }
        if (p.mapArea) {
          poly.path = JSON.parse(p.mapArea)
          let polygon = new AMap.Polygon(poly)
          polygon.name = p.name
          polygon.fillColor = p.mapColor
          polygon.id = p.targetId
          this.map.add(polygon)
          polygon.on('mouseover', this.changeStyle)
          polygon.on('mouseout', this.reCoverStyle)
        }
        // if (p.longitude && p.latitude) {
        //   console.log([p.longitude, p.latitude])
        // }
      }
    },
    changeStyle (e) {
      e.target.setOptions({
        fillOpacity: 0.5
      })
    },
    reCoverStyle (e) {
      e.target.setOptions({
        fillOpacity: 0.3
      })
    },
    getMenus () {
      let activeModule = getActiveModuleId()
      if (!activeModule) {
        this.$router.push({ path: '/' })
      } else {
        let permissionInfo = getUserPermissionTree()
        let currentMenuData = {}
        for (let i = 0; i < permissionInfo.length; i++) {
          if (activeModule === permissionInfo[i].id) {
            currentMenuData = permissionInfo[i]
          }
        }
        if (currentMenuData.length === 0) this.$router.push({ path: '/' })
        this.buildMenus(currentMenuData)
      }
    },
    buildMenus (menus) {
      if (menus && menus.name !== '系统设置' && menus.children) {
        this.menus = menus.children
      } else {
        this.menus = [menus]
      }
      this.menuList = this.menus[0].children
    },
    getItem (item, index) {
      this.panelShow = window.localStorage.getItem('currentComponentId') === item.id
      this.renderData = []
      if (!this.panelShow && this.markerList) {
        for (const key in this.markerList) {
          if (this.markerList.hasOwnProperty(key)) {
            this.markerList[key].clearData()
          }
        }
      }
      window.localStorage.setItem('currentComponentId', item.id)
      sessionStorage.setItem('currentApplicationKey', index)
      this.$router.push({path: item.uri})
      this.activePos = index * 246 + 'px'
    },
    handleClickBack () {
      sessionStorage.removeItem('currentApplicationKey')
      this.$router.push('/')
    },
    cancel () {
      this.dialogAppFormVisible = false
    }
  }
}
</script>

<style>
#shizhanContainer{
  width: 100%;
  /* height: 100%; */
  z-index: 1;
}
.custom-mapInfo-style{
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  overflow-x: hidden;
}
.custom-adhibition-header{
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  width: 100%;
  height: 129px;
  z-index: 1000;
}
.adhibition-header-l, .adhibition-header-r {
  height: 52px;
  line-height: 52px;
  flex: 1;
  background: url('../assets/application/nav_bj_01.png') repeat-x center center;
}
.adhibition-header-m {
  position: relative;
  flex:0 0 100%;
  width: 100%;
  padding-top: 46px;
  max-width: 1920px;
  background: url('../assets/application/nav_bj.png') no-repeat center center;
}
.adhibition-header-m h1{
  text-align: center;
  padding: 0;
  height: 52px;
  line-height: 52px;
  margin: 0 auto;
  color: white;
}
.custom-adhibition-menu-style{
  width: 1215px;
  margin: 0 auto;
  height: 26px;
  line-height: 26px
}
.custom-adhibition-menu-style ul{
  position: relative;
  display: flex;
  justify-content: space-around;
  color: white;
  font-size: 14px;

}
.custom-adhibition-menu-style ul li{
  flex: 1;
  line-height: 26px;
  cursor: pointer;
  text-align: center
}
.nav_active {
  position: absolute;
  width: 235px;
  height: 6px;
  bottom: -1px;
  left: 0;
  transition: all .3s;
  background: url('../assets/application/nav_active.png') no-repeat center center;
}
#panel{
  position: absolute;
  top: 140px;
  left: 20px;
  z-index: 2;
  width:250px;
  padding: 1px;
  max-height: 380px;
  overflow-y: scroll;
  background: url('../assets/application/panelLayer.png') no-repeat center center;
  cursor: default;
  border: 1px solid #1ab2ca;
  border-radius: 4px;
}
#panel::-webkit-scrollbar{
  display: none
}
#panel div{
  color: white;
}
#btnList{
  right: 0;
}
.poi-title{
  padding: 0;
  margin: 0;
}
.poi-info-left{
  padding: 4px 6px;
}
.poi-info{
  padding-top: 4px;
  font-size: 14px;
}
.backHome {
  position: absolute;
  right: 20px;
  top: 45px;
  width: 100px;
  height: 35px;
  line-height: 35px;
  text-align: center;
  font-size: 16px;
  color: #fff;
  text-decoration:none
}
#myList {
  border: none
}
#myList .el-collapse-item .el-collapse-item__header, #myList .el-collapse-item .el-collapse-item__wrap {
  background: none;
  border-radius: 0;
}
#myList .el-collapse-item .el-collapse-item__header {
  padding-left: 10px;
  font-size: 16px;
}
#myList .el-collapse-item:last-child .el-collapse-item__header {
  border: none
}
.poibox.selected {
 background:rgba(0, 0, 0, 0.5);
 color: #80ddee!important
}
.poibox.selected div {
 color: #11c0ff!important
}
.el-dialog {
  margin: 0 auto 10px;
}
</style>
